package com.lv.util;

import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lvjilei on 2018/4/2.
 */
public class HttpRequestUtil {
    private static Logger logger = Logger.getLogger(HttpRequestUtil.class);

    private static final RequestConfig REQUEST_CONFIG = RequestConfig.custom()
            .setConnectTimeout(100000).build();

    /**
     * 处理get请求
     * @param url
     * @return
     */
    public static String sendGetRequest(String url){
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(REQUEST_CONFIG);
        return sendGetRequest(httpGet);
    }

    /**
     * 处理get请求
     * @param httpGet
     * @return
     */
    public static String sendGetRequest(HttpGet httpGet){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            /**
             * 发送get请求
             */
            response = httpClient.execute(httpGet);
            /**
             * 请求发送成功并获得响应
             */
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                /**
                 * 读取服务器返回的json字符串数据
                 */
                String re = EntityUtils.toString(response.getEntity(),"UTF-8");
                return re;
            }
        } catch (IOException e) {
            logger.info("httpGet请求异常",e);

        } finally {

            try {
                if(response != null){
                    response.close();
                }
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    /**
     * 处理post请求无参数
     * @param httpUrl
     * @return
     */
    public static String sendPostRequest(String httpUrl){
        HttpPost httpPost = new HttpPost(httpUrl);
        return sendPostRequest(httpPost);
    }

    /**
     * 处理post请求 参数类型为key=value&key2=value2
     * @param httpUrl
     * @param params
     * @return
     */
    public static String sendPostReqeust(String httpUrl,String params){
        HttpPost httpPost = new HttpPost(httpUrl);
        StringEntity entity = new StringEntity(params,"UTF-8");
        entity.setContentType("application/x-www-form-urlencoded");
        httpPost.setEntity(entity);
        return sendPostRequest(httpPost);
    }

    /**
     * 处理post请求
     * @param httpUrl
     * @param maps
     * @return
     */
    public static String sendPostReqeust(String httpUrl,Map<String,String> maps){
        HttpPost httpPost = new HttpPost(httpUrl);
        /**
         * 创建参数队列
         */
        List<NameValuePair> nameValuesPairs = new ArrayList<>();

        for (String key : maps.keySet()){
            nameValuesPairs.add(new BasicNameValuePair(key,maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuesPairs,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return sendPostRequest(httpPost);
    }

    /**
     * 处理post请求
     * @param httpPost
     * @return
     */
    public static String sendPostRequest(HttpPost httpPost){
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(REQUEST_CONFIG);
            /**
             * 发送get请求
             */
            response = httpClient.execute(httpPost);
            /**
             * 请求发送成功并获得响应
             */
            if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                /**
                 * 读取服务器返回的json字符串数据
                 */
                String re = EntityUtils.toString(response.getEntity(),"UTF-8");
                return re;
            }
        } catch (IOException e) {
            logger.info("httpPost请求异常",e);

        } finally {

            try {
                if(response != null){
                    response.close();
                }
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }

    public static void main(String[] args) throws InterruptedException {
        Map<String,String> maps = new HashMap<>();
        JSONArray jsonArray = getParamsArray("/Users/lvjilei/Desktop/address.txt");
        maps.put("addresses",jsonArray.toString());
        long start = System.currentTimeMillis();
        //String str = HttpRequestUtil.sendPostReqeust("http://127.0.0.1:18082/ogsp/ungeocoder",maps);
        String str = HttpRequestUtil.sendPostReqeust("http://192.168.20.201:18082/ogsp/geocoder",maps);
        System.out.println(str);
        JSONArray res = new JSONArray(str);
        long end = System.currentTimeMillis();
        System.out.println("耗时:"+((end-start)));
    }


    public static JSONArray getParamsArray(String location){
        JSONArray jsonArray = new JSONArray();
        BufferedReader br = null;
        String line = "";
        try {
            br = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(location),"UTF-8"));
            while(null != (line = br.readLine())){
                jsonArray.put(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonArray;
    }
}
